package com.fingard.dsp.bank.directbank.mufg01;

import java.io.File;
import java.util.*;

import com.fingard.dsp.bank.directbank.bankInterface.IFileResolveDifference;
import com.fingard.io.FileHelper;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;

public class MUFG01ForeignBank extends MUFG01Base implements IFileResolveDifference {
    /**
     * MT942中获取期初余额，当前余额，当前可用余额，上次交易后的余额
     * @return
     */
    public Map<String,String> getBalanceMap(String context, String accountNum, String date) throws Exception{
        /*//获取出账总金额
        int offset = context.indexOf(tag90D) + tag90D.length();
        int endset = context.indexOf(tag90C);
        String outBal = context.substring(offset, endset);
        int startIndex=indexLength(outBal.replace(",","").trim());
        outBal = outBal.substring(startIndex + 1).replaceAll(",", ".")
                .replaceAll("\r", "").replaceAll("\n", "");
        outBal = amtCheck(outBal);
        //获取入账总金额
        offset = context.indexOf(tag90C) + tag90C.length();
        endset = context.indexOf(tag86);
        String inBal = context.substring(offset, endset);
        startIndex=indexLength(inBal.replace(",","").trim());
        inBal = inBal.substring(startIndex+1).replaceAll(",", ".")
                .replaceAll("\r", "").replaceAll("\n", "");
        inBal = amtCheck(inBal);
        //获取账户币种
        offset = context.indexOf(tag34F) + tag34F.length();
        String cur = context.substring(offset, offset + 3);
        //获取余额相关信息
        String openBal="0.00";//期初
        String closeBal="0.00";//当前
        String availBal="0.00";//当前可用
        //当前余额=34F节点余额+90c-90d；
        offset = context.indexOf(tag34F) + tag34F.length();
        endset =context.indexOf(tag13D);
        openBal=context.substring(offset+3,endset).replace(",", ".").replace("\r","").replace("\n","");
        openBal = amtCheck(openBal);
        closeBal=new BigDecimal(openBal).add(new BigDecimal(inBal)).subtract(new BigDecimal(outBal)).toString();
        closeBal = amtCheck(closeBal);
        //不存在MT942文件，说明是当天的第一个MT942，
        //期初余额=上日当前余额；当前可用余额=940上日可用余额+90c-90d
        String balFilePath = getBankConfig().getValueAsString("DealedPath") + File.separator + date + File.separator
                + "MT942" + File.separator + accountNum + "_7506.txt";
        if(!FileHelper.existFile(balFilePath)){
            Calendar calendarToday=Calendar.getInstance();
            calendarToday.setTime(Format.Date8Format.parse(date));
            calendarToday.add(Calendar.DAY_OF_MONTH,-1);
            int num =1;//初始遍历天数
            String day=getBankConfig().getValueAsString("countDay");//往前遍历天数
            String dealedFile = getBankConfig().getValueAsString("DealedPath")+ File.separator+
                    Format.Date8Format.format(calendarToday.getTime())+
                    File.separator+"MT940"+File.separator+accountNum+"_7505.txt";
            while(!FileHelper.existFile(dealedFile)&&num<=Integer.parseInt(StringHelper.isNullOrEmpty(day) ?"10":day)){
                WriteBankLogLn("账户"+accountNum+"在"+Format.Date8Format.format(calendarToday.getTime())+"日期的MT940文件不存在,继续往前一天遍历，第"+num+"次");
                calendarToday.add(Calendar.DAY_OF_MONTH,-1);
                dealedFile = getBankConfig().getValueAsString("DealedPath")+File.separator+
                        Format.Date8Format.format(calendarToday.getTime())+
                        File.separator+"MT940"+File.separator+accountNum+"_7505.txt";
                num++;
            }
            //读取文件内容
            String balContent = FileHelper.readFileText(dealedFile,getCharset());
            WriteBankLogLn("读取到的文件内容："+balContent);
            if(StringHelper.hasAnyChar(balContent)){//存在MT940
                String[] bal  =balContent.split("\\|");
                if(bal.length>3){
                    //期初余额
                    openBal=bal[2];
                    //当前余额
                    //closeBal=new BigDecimal(openBal).add(new BigDecimal(inBal)).subtract(new BigDecimal(outBal)).toString();
                    //当前可用余额
                    availBal=new BigDecimal(bal[3]).add(new BigDecimal(inBal)).subtract(new BigDecimal(outBal)).toString();
                }
            }else {//不存在MT940文件
                //期初余额
                offset = context.indexOf(tag34F) + tag34F.length();
                endset =context.indexOf(tag13D);
                openBal=context.substring(offset+3,endset).replace(",", ".").replace("\r","").replace("\n","");
                openBal = amtCheck(openBal);
                //当前余额 期初余额+90c-90d
                //closeBal=new BigDecimal(openBal).add(new BigDecimal(inBal)).subtract(new BigDecimal(outBal)).toString();
                //closeBal = amtCheck(closeBal);
                //当前可用
                availBal=closeBal;
            }
        }else {
            //读取文件内容：存在MT942文件 可用余额=上一次可用余额+90c-90d
            String balContent = FileHelper.readFileText(balFilePath,getCharset());
            WriteBankLogLn("读取到的文件内容："+balContent);
            if(StringHelper.hasAnyChar(balContent)){
                String[] bal  =balContent.split("\\|");
                if(bal.length>4){
                    //期初余额
                    openBal=bal[4];
                    //当前余额
                    //closeBal=new BigDecimal(bal[2]).add(new BigDecimal(inBal)).subtract(new BigDecimal(outBal)).toString();
                    //当前可用余额
                    availBal=new BigDecimal(bal[3]).add(new BigDecimal(inBal)).subtract(new BigDecimal(outBal)).toString();
                }
            }
        }
        //计算该账户上一次的当前余额：当前余额-入账+出账
        BigDecimal bigDecimal = new BigDecimal(closeBal);
        String lastBal = bigDecimal.add(new BigDecimal(outBal)).subtract(new BigDecimal(inBal)).toString();
        //返回
        Map<String,String> map=new HashMap<String, String>();
        map.put("closeBal",closeBal);
        map.put("availBal",availBal);
        map.put("openBal",openBal);
        map.put("lastBal",lastBal);
        return map;*/
        return null;
    }

    /**
     * 解析86字符串获取对手信息：对方账号，对方户名，对方银行名称，附言
     * @param string86
     * @return
     * @throws Exception
     */
    public Map<String,String> getRecInformationMap(String string86){
        /*//定义元素
        String recAct = "";//对方账户
        String recName = "";//对方名称
        String recBankName="";//对方银行名称
        String recDetail = "";//备注
        //解析字符串获取值
        *//*String[] content86=string86.split("\r\n");
        List<String> list = Arrays.asList(content86);
        for(String content:list){
            //对方账户
            if(content.contains(pooling)){
                int start= content.trim().indexOf(":")+4;
                recAct=content.trim().substring(start);
            }
            //对方名称
            if(content.contains(ord)){
                recName = content.trim().replace(ord,"");
            }
            //对方银行名称
            if(content.contains(ben)){
                recBankName = content.trim().replace(ben,"");
            }
            //用途
            if (content.contains(tra)) {
                recDetail = content.trim().replace(tra,"");
            }
        }*//*
        //用途
        recDetail=string86;
        //返回值
        Map<String,String> map=new HashMap<String, String>();
        map.put("recAct",recAct);
        map.put("recName",recName);
        map.put("recBankName",recBankName);
        map.put("recDetail",recDetail);
        return map;*/
        return null;
    }

    /**
     * 解析付款响应文件
     * @param filePath
     * @throws Exception
     */
    @Override
    public void analysisAckFile(String filePath) throws Exception {
        String ackFilePath=StringHelper.trimEndFileSp(getBankConfig().getValueAsString("DealedPath"));
        String[] rspStatus=new String[]{"","",""};
        if(FileHelper.existFile(filePath)){
            //解析文件名
            String fileName=new File(filePath).getName();
            String[] fileArr=fileName.contains(".")?fileName.substring(0,fileName.indexOf(".")).split("_"):fileName.split("_");
            String content=FileHelper.readFileText(filePath,getCharset());
            WriteBankLogLn("获取ack文件内容为："+content);
            //说明是Lv1级响应
            if(StringHelper.hasAnyChar(content) && content.contains(ackFlag) && content.contains(askStartFlag)){
                WriteBankLogLn("检测到ack-Lv.1文件开始处理");
                if(fileArr.length==3){
                    //获取流水号
                    rspStatus[0]=fileArr[2];
                    //获取交易时间
                    String payDate="20"+fileArr[0].substring(8);//从第8位开始截取
                    //获取状态码
                    String ackContent=content.substring(content.indexOf(ackFlag)+ackFlag.length());
                    String status=ackContent.substring(ackContent.indexOf(":")+1);
                    status=status.replaceAll(" ","").replace("\r","").replace("\n","");
                    if(StringHelper.hasAnyChar(status) && "1".equals(status.substring(0,1))){
                        rspStatus[1]="RJCT";
                        //rspStatus[2]="交易被拒绝：响应码"+status+"，详情请参照StatusCode_Payments文档";
                        //WriteBankLogLn(rspStatus[0]+"的Lv1响应状态码为："+status);
                    }else if(StringHelper.hasAnyChar(status) && "0".equals(status.substring(0,1))){
                        rspStatus[1]="ACCP";
                        //rspStatus[2]="交易处理中：响应码"+status+"，详情请参照StatusCode_Payments文档";
                        //WriteBankLogLn(rspStatus[0]+"的Lv1响应状态码为："+status);
                    }else if (StringHelper.hasAnyChar(status) && "2".equals(status.substring(0,1))){
                        rspStatus[1]="PART";
                        //rspStatus[2]="交易处理中：响应码"+status+"，详情请参照StatusCode_Payments文档";
                        //WriteBankLogLn(rspStatus[0]+"的Lv1响应状态码为："+status);
                    }
                    rspStatus[2]="响应码："+status+"，响应信息："+getBankConfig().getMapValueByKey("resultMapping",status);
                    WriteBankLogLn(rspStatus[0]+"的Lv1响应状态码为："+status);
                    //生成ack处理文件
                    getAckStatus(ackFilePath,payDate,rspStatus,"1");
                    WriteBankLogLn("ack-Lv.1文件已处理");
                }else {
                    WriteBankLogLn("文件名格式异常");
                    throw new Exception("文件名"+fileName+"格式异常");
                }
                //说明是Lv2 or Lv3级响应
            } else if(StringHelper.hasAnyChar(content) && content.contains("OrgnlGrpInfAndSts")){
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(content,tmpSbMsg);
                if(tmpBkReader!=null) {
                    String orgnlMsgId=tmpBkReader.getFirstText("/Document/CstmrPmtStsRpt/OrgnlGrpInfAndSts/OrgnlMsgId");
                    //Lv.3
                    if(StringHelper.hasAnyChar(orgnlMsgId)){
                        WriteBankLogLn("检测到ack-Lv.3文件开始处理");
                        while (tmpBkReader.read("/Document/CstmrPmtStsRpt/OrgnlPmtInfAndSts")){
                            //支付流水号
                            rspStatus[0]=tmpBkReader.readedXElement.getSingleChild("TxInfAndSts").getSingleTextNotNull("OrgnlEndToEndId");
                            if(rspStatus[0].equals(fileArr[2])){//支付流水号匹配
                                //状态码
                                rspStatus[1]=tmpBkReader.readedXElement.getSingleChild("TxInfAndSts").getSingleTextNotNull("TxSts").trim();
                                //付款时间
                                String payDate="20"+fileArr[0].substring(8);//从第8位开始截取
                                //描述信息
                                String status=tmpBkReader.readedXElement.getSingleChild("TxInfAndSts").getSingleChild("StsRsnInf")
                                        .getSingleChild("Rsn").getSingleTextNotNull("Prtry").trim();
                                /*if(StringHelper.hasAnyChar(status) && "1".equals(status.substring(0,1))){
                                    rspStatus[2]="交易被拒绝：响应码"+status+"，详情请参照StatusCode_Payments文档";
                                    WriteBankLogLn(rspStatus[0]+"的Lv3响应状态码为："+status);
                                }else {
                                    rspStatus[2]="交易处理中：响应码"+status+"，详情请参照StatusCode_Payments文档";
                                    WriteBankLogLn(rspStatus[0]+"的Lv3响应状态码为："+status);
                                }*/
                                rspStatus[2]="响应码："+status+"，响应信息："+getBankConfig().getMapValueByKey("resultMapping",status);
                                WriteBankLogLn(rspStatus[0]+"的Lv3响应为："+rspStatus[2]);
                                //生成ack处理文件
                                getAckStatus(ackFilePath,payDate,rspStatus,"3");
                                WriteBankLogLn("ack-Lv.3文件已处理");
                            }
                        }
                    }else {//Lv.2
                        WriteBankLogLn("检测到ack-Lv.2文件开始处理");
                        if(fileArr.length==3){
                            String payDate="20"+fileArr[0].substring(8);//从第8位开始截取
                            rspStatus[0]=fileArr[2];
                            rspStatus[1]=tmpBkReader.getFirstText("/Document/CstmrPmtStsRpt/OrgnlGrpInfAndSts/GrpSts").trim();
                            String status=tmpBkReader.getFirstText("/Document/CstmrPmtStsRpt/OrgnlGrpInfAndSts/StsRsnInf/Rsn/Prtry").trim();
                            /*if(StringHelper.hasAnyChar(status) && "1".equals(status.substring(0,1))){
                                rspStatus[2]="交易被拒绝：响应码"+status+"，详情请参照StatusCode_Payments文档";
                                WriteBankLogLn(rspStatus[0]+"的Lv2响应状态码为："+status);
                            }else if(StringHelper.hasAnyChar(status) && "0".equals(status.substring(0,1))){
                                rspStatus[2]="交易处理中：响应码"+status+"，详情请参照StatusCode_Payments文档";
                                WriteBankLogLn(rspStatus[0]+"的Lv2响应状态码为："+status);
                            }else if (StringHelper.hasAnyChar(status) && "2".equals(status.substring(0,1))){
                                rspStatus[2]="交易处理中：响应码"+status+"，详情请参照StatusCode_Payments文档";
                                WriteBankLogLn(rspStatus[0]+"的Lv2响应状态码为："+status);
                            }*/
                            rspStatus[2]="响应码："+status+"，响应信息："+getBankConfig().getMapValueByKey("resultMapping",status);
                            WriteBankLogLn(rspStatus[0]+"的Lv2响应为："+rspStatus[2]);
                            //生成ack处理文件
                            getAckStatus(ackFilePath,payDate,rspStatus,"2");
                            WriteBankLogLn("ack-Lv.2文件已处理");
                        }
                    }
                }else {
                    WriteBankLogLn("文件"+filePath+"异常："+tmpSbMsg.toString());
                    throw new Exception("文件"+filePath+"异常："+tmpSbMsg.toString());
                }
            }else {
                WriteBankLogLn("文件"+filePath+"非Lv1、Lv2、Lv3文件");
                throw new Exception("文件"+filePath+"非Lv1、Lv2、Lv3文件");
            }
        }else{
            WriteBankLogLn("文件"+filePath+"不存在");
            throw new Exception("文件"+filePath+"不存在");
        }
    }
}
